﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Mysoft.QuickCode.ServiceProvider
{
    public class BaseService
    {
        public Dictionary<string, Func<ServiceRequest, ServiceResponse>> Functions =
            new Dictionary<string, Func<ServiceRequest, ServiceResponse>>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// 初始化，将对象中匹配的委托方法自动装载到委托字典。
        /// </summary>
        /// <param name="obj">要加载方法的对象</param>
        public BaseService(object obj)
        {
            MethodInfo[] methods = obj.GetType().GetMethods();
            foreach (MethodInfo mi in methods)
            {
                ParameterInfo[] pis = mi.GetParameters();
                //找到对应的格式方法：只有一个参数，参数类型为ServiceRequest，且返回值类型为ServiceResponse
                if (pis.Length == 1
                    && pis[0].ParameterType == typeof(ServiceRequest)
                    && mi.ReturnType == typeof(ServiceResponse))
                {
                    ParameterExpression paramExp = Expression.Parameter(typeof(ServiceRequest), "ServiceRequest");
                    MethodCallExpression callExp = Expression.Call(Expression.Constant(obj), mi, paramExp);
                    Expression<Func<ServiceRequest, ServiceResponse>> lambda = Expression.Lambda<Func<ServiceRequest, ServiceResponse>>(callExp, paramExp);
                    Func<ServiceRequest, ServiceResponse> fun = lambda.Compile();
                    Functions.Add(mi.Name, fun);
                }
            }
        }
    }
}
